import {
  reqOrderGoodsList,
  reqOrderBuyGoods,
  reqOrderUserInfo,
  reqSubmitOrder,
  reqGetPayInfo,
  reqPayResult
} from '../../api/index';
import moment from 'moment';
Page({

  data: {
    cartVoList: [], //订单页展示的商品
    totalAmount: 0, //支付的总钱数
    goodsId: '', //商品的ID
    blessing: '', //祝福语
    user: {}, //默认收货人信息
    showPop: false, //日期弹窗
    miniDate: new Date().getTime(),
    //收集提交订单参数
    buyName: '', //订购人的名字
    buyPhone: '', //订购人的手机号码
    deliveryDate: '', //预计送达的日期
  },

  //页面加载成功
  onLoad(option) {
    //立即购买而来
    if (option.blessing) {
      //存储商品的ID|祝福语
      this.setData({
        goodsId: option.goodsId,
        blessing: option.blessing
      });
      //获取立即购买的商品的信息
      this.getBuyGoods();


    } else {
      //购物车而来
      this.getCartGoodsList();
    }
    //获取收货人信息地址
    this.getUserAddress();
  },
  //获取购物车全部商品在订单页渲染
  async getCartGoodsList() {
    const result = await reqOrderGoodsList();
    if (result.code == 200) {
      this.setData({
        totalAmount: result.data.totalAmount,
        cartVoList: result.data.cartVoList
      })
    }
  },
  //获取客户立即购买的商品的信息
  async getBuyGoods() {
    const {
      goodsId,
      blessing
    } = this.data;
    const result = await reqOrderBuyGoods(goodsId, blessing);
    if (result.code == 200) {
      this.setData({
        totalAmount: result.data.totalAmount,
        cartVoList: result.data.cartVoList
      })
    }
  },
  async getUserAddress() {
    const result = await reqOrderUserInfo();
    if (result.code == 200) {
      this.setData({
        user: result.data
      })
    }
  },
  //提交订单(去结算按钮)
  async submitOrder() {
    // 整理参数
    const data = {
      buyName: this.data.buyName,
      buyPhone: this.data.buyPhone,
      cartList: this.data.cartVoList,
      deliveryDate: this.data.deliveryDate,
      remarks: this.data.blessing,
      userAddressId: this.data.user.id
    }
    //提交订单请求获取订单号
    const result = await reqSubmitOrder(data);
    if (result.code === 200) {
      const payInfo = await reqGetPayInfo(result.data);
      wx.requestPayment({
        nonceStr: payInfo.data.nonceStr,
        package: payInfo.data.package,
        paySign: payInfo.data.paySign,
        timeStamp: payInfo.data.timeStamp,
        signType: payInfo.data.signType,
        async success() {
          const successResult = await reqPayResult(result.data);  
          if (successResult.code === 200) {
            wx.navigateTo({
              url: '/pages/success/success',
            })
          }
        }
      })
    }
  },
  // 点击期望送达日期，弹出Pop
  HopeTime() {
    this.setData({
      showPop: true
    })
  },
  //点击pop遮罩层
  overPlay() {
    this.setData({
      showPop: false
    })
  },
  //日期确定按钮的回调
  conformDate(event) {
    this.setData({
      showPop: false,
      deliveryDate: moment(event.detail).format('YYYY-MM-DD')
    })
  }
})